#!/usr/bin/env python
#-*- coding: utf-8 -*-


# PacoDbg - an advanced RCE analysis debugger
# Copyright (C) 2013 The PacoDbg contributers

# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.


__all__ = ["PalleteError",
           "Pallete"]


import os


PALLETE_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), 'palletes'))
DEFAULT_PALLETE = 'default.ptte'


class PalleteError(StandardError):
    pass


class Pallete(object):
    def __new__(cls, pallete=DEFAULT_PALLETE, pallete_path=PALLETE_PATH):
        try:
            p_fl = os.path.join(pallete_path, pallete)
            p_str = open(p_fl, 'r').read()
            p_struct = eval(p_str)
            
            return cls._to_pallete(p_struct)
        except Exception, err:
            raise PalleteError("Could not load pallete %s from %s" % (pallete, pallete_path))
    
    @classmethod
    def _to_pallete(cls, p_struct):
        p = []
        for plt in p_struct:
            if len(plt) == 3:
                item = (plt[0], ','.join(plt[1]) if isinstance(plt[2], tuple) else plt[1], plt[2])
            elif len(plt) == 4:
                item = (plt[0], ','.join(plt[1]) if isinstance(plt[2], tuple) else plt[1], plt[2], plt[3])
            else:
                continue
            p.append(item)
        
        return p
